﻿/*
 * The MIT License
 * 
 * Copyright 2008 Jeppe Burchardt and Pimm Hogeling
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

package org.dr.actionconsole.data
{
	import flash.utils.Dictionary;
	public class CommandData
	{
		private var _help : String;
		private var _listener : Dictionary;
		private var aliases : Array;
		private var argumentTags : Array;
		public var id : String;
		public function CommandData(match:String, listener:Function, help:String=null, argumentTags:Array=null, useWeakReference:Boolean=false) : void
		{
			id = match;
			aliases = new Array();
			_listener = new Dictionary(useWeakReference);
			_listener[listener] = "listener";
			_help = help;
			this.argumentTags = argumentTags;
		}
		public function addAlias(alias:String) : CommandData
		{
			aliases.push(alias);
			return this;
		}
		public function get help() : String
		{
			if (_help && _help !== "")
			{
				return _help;
			}
			else
			{
				return "No help available";
			}
		}
		public function get listener() : Function
		{
			for (var f:* in _listener)
			{
				return f;
			}
			return null;
		}
		public function matches(input:String) : Boolean
		{
			if (this.id === input)
			{
				return true;
			}
			for each (var id:String in aliases)
			{
				if (id === input)
				{
					return true
				}
			}
			return false;
		}
		public function removeAlias(alias:String) : Boolean
		{
			var i : int = -1;
			const l : uint = aliases.length;
			while (++i < l)
			{
				if (aliases[i] === alias)
				{
					aliases.splice(i, 1);
					return true;
				}
			}
			return false;
		}
		public function get usage() : String
		{
			if (argumentTags && argumentTags.length)
			{
				var close : String = "";
				var i : uint = 0;
				const l : uint = argumentTags.length + 1;
				while (++i < l)
				{
					close += "]";
				}
				return id + " [" + argumentTags.join(", [") + close;
			}
			else
			{
				return id;
			}
		}
	}
}